package cn.edu.ljl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

//用来添加用户信息
//添加成功后、进入提示注册成功界面，使用comSign.html
//如果添加未成功，会重新回到注册界面，使用SignIn.html
//如果用户名已被注册，会进行提示并再次进入注册界面，使用RESignADD.html


public class addSign extends HttpServlet {
    private static final String INSERT_TEMPLATE =
            "INSERT INTO sign (`nam`, `password`) " + "VALUES ('%s', '%s')";

    private static final String SELECT =
            "SELECT * FROM sign ";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String name = request.getParameter("nam");
        String password = request.getParameter("password");
        String password01 = request.getParameter("password01");

        try {
            List<sign> signs = DBMS.getSigns(SELECT);
            response.setCharacterEncoding("UTF-8");
            Writer writer = response.getWriter();
            StringBuilder sb = new StringBuilder();

            String UserName = name;
            int i = 0;
            for (i = 0; i < signs.size(); i++) {
                sign s = signs.get(i);
                if (UserName.equals(s.getName())) {
                    break;

                }
            }
            if (i == signs.size()) {
                if (password.equals(password01)) {


                    String sql = String.format(INSERT_TEMPLATE, name, password);
                    System.out.println(sql);


                    try {
                        DBMS.insert(sql);
                        response.sendRedirect("./comSign.html");
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    response.sendRedirect("./SignIn.html");
                }
                return;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.sendRedirect("./RESignADD.html");
    }
}
